from django_redis import get_redis_connection

import pickle
import base64


# 登录合并购物车
def merge_cart_cookie_to_redis(request, user, response):
    # 获取cookie中的购物车数据
    cart_str = request.COOKIES.get('cart')
    if not cart_str:
        return response
    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))  # 字典
    # {
    #     3:{
    #         'count':30,
    #         'selected':true
    #     }
    # }

    # 获取redis中的购物车数据
    redis_conn = get_redis_connection('carts')
    redis_conn_dict = redis_conn.hgetall('cart_%s' % user.id)
    # 存储数据方式redis_conn_dict = {b'1':b'10', b'2':b'20'}
    # 将原始的购物车数据类型装换， 由bytes转为int
    new_conn_dict = {}
    for sku_id, count in redis_conn_dict.items():
        new_conn_dict[int(sku_id)] = int(count)
    # 读取出哪些商品被勾选了
    redis_selected_list = redis_conn.smembers('selected_%s' % user.id)
    # redis_selected_list = [b'1', b'2']
    # 将两个数据合并存入redis中
    for sku_id, cookie_dict in cart_dict.items():
        new_conn_dict[sku_id] = cookie_dict['count']
        if cookie_dict['selected']:
            redis_selected_list.add(sku_id)

    # 将数据写入到redis中
    # 管道
    pl = redis_conn.pipeline()
    pl.hmset('cart_%s' % user.id, new_conn_dict)
    pl.sadd('selected_%s' % user.id, *redis_selected_list)
    pl.execute()

    # 删除cookie中的数据
    response.delete_cookie('cart')

    return response